<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;

/**
 * 商品
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\goods\Goods
     */
    protected $model = null;

    
    protected $noNeedLogin = [];
    protected $noNeedRight = ['store_list','setsalestore'];

    protected $categoryModel = null;

    public function _initialize()
    {
        parent::_initialize();

        $this->categoryModel = new \app\admin\model\goods\Category;
        $tree = Tree::instance();
        $tree->init(collection($this->categoryModel->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }
//        $this->view->assign("flagList", $this->categoryModel->getFlagList());

        $this->view->assign("parentList", $categorydata);
        //var_dump($categorydata);die;

        $this->model = new \app\admin\model\goods\Goods;
        // $this->view->assign("newStatusList", $this->model->getNewStatusList());
        // $this->view->assign("starStatusList", $this->model->getStarStatusList());
        // $this->view->assign("indexStatusList", $this->model->getIndexStatusList());
    }



    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        //var_dump($sort, $order);die;
        $list = $this->model
            ->where($where)
            ->order('sort desc')
            ->order('id desc')
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $params['cate_id'] = db('goodscate')->where('id',$params['cate_id2'])->value('pid');
            if (empty($params['cate_id']) || empty($params['cate_id2'])) {
                $this->error('分类错误');
            }
            $result = $this->model->allowField(true)->save($params);
            
            
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $params['cate_id'] = db('goodscate')->where('id',$params['cate_id2'])->value('pid');
            if (empty($params['cate_id']) || empty($params['cate_id2'])) {
                $this->error('分类错误');
            }
            $result = $row->allowField(true)->save($params);

          

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
     /**
     * 编辑基础信息
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit_jichu($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $params['cate_id'] = db('goodscate')->where('id',$params['cate_id2'])->value('pid');
            if (empty($params['cate_id']) || empty($params['cate_id2'])) {
                $this->error('分类错误');
            }
            $result = $row->allowField(true)->save($params);

            db('store_goods')->where(['goods_id'=>$ids])->update(['cate_id'=>$params['cate_id'],'cate_id2'=>$params['cate_id2']]);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    //设置商品推荐状态
    public function setFlag()
    {
        $id = $this->request->param('id');
        $type = $this->request->param('type');
        $status = $this->request->param('status');
        db('goods')->where('id',$id)->update([
            $type => $status,
        ]);
        return json([
            'code'=>1,
            'msg'=>'修改成功'
        ]);
    }

    //中心空间列表
    public function store_list()
    {
        //当前是否为关联查询
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //$admininfo=$this->auth->getUserInfo();
            $where_admin=['is_del'=>'0'];
            $where_admin=['is_ban'=>'0'];
            //$where_admin=['is_card_pay'=>'1'];
            //var_dump($sort,$order);die;
            $list = $this->store_model
                    ->where($where)
                    ->where($where_admin)
                    ->order($sort, $order)
                    ->paginate(1000000);
                    //var_dump($this->model->getLastsql());die;
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        $goodsid = $this->request->param('goodsid');
        $goods_name = db('goods')->where('id',$goodsid)->value('goods_name');
        $this->assignconfig('goodsid',$goodsid);
        $this->view->assign('goods_name',$goods_name);
        return $this->view->fetch();
    }

    //设置产品可售卖的空间
    public function setsalestore()
    {
        $storeids = $this->request->param('ids');
        $storeidsyes = $this->request->param('idsyes');
        $goods_id = $this->request->param('goods_id');
        if (empty($goods_id)) {
            $this->error('参数错误');
        }
        
        if (!empty($storeids)) {
            $storeids = explode(',',$storeids);
            //不能卖的
            foreach ($storeids as $key => $value) {
                $notGoods = db('store')->where('id',$value)->value('not_goods');
                if (empty($notGoods)) {
                    $notGoods = $goods_id;
                } else {
                    $notgoodsarr = explode(',',$notGoods);
                    if (in_array($goods_id,$notgoodsarr)) {
                        
                    } else {
                        $notGoods = $notGoods.','.$goods_id;
                    }
                }
                db('store')->where('id',$value)->update([
                    'not_goods'=>$notGoods
                ]);
            }
        }
        

        if (!empty($storeidsyes)) {
            $storeidsyes = explode(',',$storeidsyes);
            //能卖的
            foreach ($storeidsyes as $k => $v) {
                $notGoods = db('store')->where('id',$v)->value('not_goods');
                if (empty($notGoods)) {
                    
                } else {
                    $notgoodsarr = explode(',',$notGoods);
                    if (in_array($goods_id,$notgoodsarr)) {
                        $key = array_search($goods_id, $notgoodsarr);
                        unset($notgoodsarr[$key]);
                        $notGoods = implode(',',$notgoodsarr);
                    }
                }
                db('store')->where('id',$v)->update([
                    'not_goods'=>$notGoods
                ]);
            }
        }
        
        $this->success('设置成功');
    }
}
